package com.yonyou.cloud.member.domainmodel.services.impl;

import com.yonyou.cloud.member.domainmodel.entities.coupon.Coupon;
import com.yonyou.cloud.member.domainmodel.vo.CouponId;
import com.yonyou.cloud.member.domainmodel.entities.coupon.CouponStatusEnum;
import com.yonyou.cloud.member.domainmodel.vo.MemberId;
import com.yonyou.cloud.member.domainmodel.repositories.CouponRepository;
import com.yonyou.cloud.member.domainmodel.services.CouponService;
import com.yonyou.cloud.member.exceptions.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CouponServiceImpl implements CouponService {
    @Autowired
    CouponRepository couponRepository;

    @Override
    public List<Coupon> effectiveCoupons(MemberId memberId) {
        return couponRepository.listByMember(memberId);
    }

    // @Transcational
    @Override
    public Boolean consume(CouponId couponId) {
        Coupon coupon = couponRepository.find(couponId);
        if (coupon == null) {
            throw new BusinessException("卡券不存在");
        }
        if (coupon.getStatus() == CouponStatusEnum.CONSUMED) {
            throw new BusinessException("卡券已经被消费");
        }
        return couponRepository.updateStatus(couponId, CouponStatusEnum.CONSUMED);
    }

    @Override
    public Boolean reset() {
        return couponRepository.reset();
    }
}
